Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(arq): incidents processing #2558

Merged
merged 2 commits into from
Nov 20, 2024

Conversation

talboren
Copy link
Member

@talboren talboren commented Nov 20, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced job queuing for incident processing by specifying a dedicated queue.
    • Improved logging capabilities in the incident processing function, providing better tracking of job attempts and identifiers.
  • Bug Fixes

    • Clarified response behavior when alerts are successfully added to incidents by explicitly stating the response status code.

@talboren talboren linked an issue Nov 20, 2024 that may be closed by this pull request
Copy link

vercel bot commented Nov 20, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
keep ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 20, 2024 0:47am

@dosubot dosubot bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Nov 20, 2024
Copy link

coderabbitai bot commented Nov 20, 2024

Walkthrough

The changes in this pull request involve modifications to two functions within the keep/api/routes/incidents.py and keep/api/tasks/process_incident_task.py files. The receive_event function now includes a _queue_name parameter for specifying the queue for job processing, while the add_alerts_to_incident function explicitly states its response type. In the process_incident function, additional logging capabilities are introduced to capture context information related to job processing attempts, enhancing the error handling without altering the existing logic.

Changes

File Path Change Summary
keep/api/routes/incidents.py - Modified receive_event to include _queue_name parameter for job queuing.
- Updated add_alerts_to_incident to explicitly declare response type as Response.
keep/api/tasks/process_incident_task.py - Enhanced process_incident to log additional context information (job_try, job_id).
- Retained existing logic while improving logging and retry mechanism.

Possibly related issues

Poem

🐰 In the code where incidents flow,
A new queue name helps jobs to grow.
With logs that tell of tries and tales,
Our rabbit heart hops and never fails.
So let’s cheer for the changes made,
In our coding burrow, joy is laid! 🌟

Warning

Rate limit exceeded

@dosubot[bot] has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 36 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 108dee0 and 31eb789.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@dosubot dosubot bot added the Bug Something isn't working label Nov 20, 2024
@talboren talboren enabled auto-merge (squash) November 20, 2024 12:35
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (4)
keep/api/tasks/process_incident_task.py (3)

35-38: LGTM! Consider minor improvements to context extraction

The addition of job context information is valuable for tracking processing attempts. The implementation is correct, but we can make it slightly more concise.

    if ctx and isinstance(ctx, dict):
        extra["job_try"] = ctx.get("job_try", 0)
-       extra["job_id"] = ctx.get("job_id", None)
+       extra["job_id"] = ctx.get("job_id")
🧰 Tools
🪛 Ruff

37-37: Use ctx.get("job_id") instead of ctx.get("job_id", None)

Replace ctx.get("job_id", None) with ctx.get("job_id")

(SIM910)


Line range hint 156-158: Consider implementing exponential backoff for retries

The current linear retry delay (job_try * TIMES_TO_RETRY_JOB) might not be optimal for handling transient failures. Consider implementing exponential backoff to provide shorter initial retries while still allowing longer delays for persistent issues.

        # Retrying only if context is present (running the job in arq worker)
        if bool(ctx):
-           raise Retry(defer=ctx["job_try"] * TIMES_TO_RETRY_JOB)
+           # Exponential backoff with base of 2 minutes
+           raise Retry(defer=2 ** ctx["job_try"])
🧰 Tools
🪛 Ruff

37-37: Use ctx.get("job_id") instead of ctx.get("job_id", None)

Replace ctx.get("job_id", None) with ctx.get("job_id")

(SIM910)


Line range hint 101-104: Consider more specific exception handling for alerts processing

The current broad exception handling for alerts processing might mask specific issues. Consider:

  1. Catching specific exceptions that you expect might occur
  2. Adding a flag or status to the incident to indicate incomplete alert processing
  3. Including alert processing status in the pusher notification

Example implementation:

try:
    # ... alerts processing code ...
except (ValueError, KeyError) as e:
    logger.exception("Error processing alert data: %s", str(e), extra=extra)
except ConnectionError as e:
    logger.exception("Network error processing alerts: %s", str(e), extra=extra)
    incident_from_db.alert_processing_status = "incomplete"
except Exception as e:
    logger.exception("Unexpected error adding incident alerts: %s", str(e), extra=extra)
    incident_from_db.alert_processing_status = "failed"
🧰 Tools
🪛 Ruff

37-37: Use ctx.get("job_id") instead of ctx.get("job_id", None)

Replace ctx.get("job_id", None) with ctx.get("job_id")

(SIM910)

keep/api/routes/incidents.py (1)

Line range hint 1012-1034: Fix response model inconsistency

The endpoint decorator specifies response_model=List[AlertDto], but the function returns a Response(status_code=202). This mismatch could cause issues with OpenAPI documentation and client expectations.

Apply this fix:

@router.post(
    "/{incident_id}/alerts",
    description="Add alerts to incident",
    status_code=202,
-   response_model=List[AlertDto],
)
async def add_alerts_to_incident(
    incident_id: UUID,
    alert_ids: List[UUID],
    is_created_by_ai: bool = False,
    authenticated_entity: AuthenticatedEntity = Depends(
        IdentityManagerFactory.get_auth_verifier(["write:incident"])
    ),
    pusher_client: Pusher | None = Depends(get_pusher_client),
    session: Session = Depends(get_session),
):
    tenant_id = authenticated_entity.tenant_id
    incident_bl = IncidentBl(tenant_id, session, pusher_client)
    await incident_bl.add_alerts_to_incident(incident_id, alert_ids)
    return Response(status_code=202)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 108dee0 and 31eb789.

📒 Files selected for processing (2)
  • keep/api/routes/incidents.py (1 hunks)
  • keep/api/tasks/process_incident_task.py (1 hunks)
🧰 Additional context used
🪛 Ruff
keep/api/tasks/process_incident_task.py

37-37: Use ctx.get("job_id") instead of ctx.get("job_id", None)

Replace ctx.get("job_id", None) with ctx.get("job_id")

(SIM910)

🔇 Additional comments (1)
keep/api/routes/incidents.py (1)

552-552: LGTM! Queue specification for incident processing

The addition of _queue_name=KEEP_ARQ_QUEUE_BASIC properly directs incident processing jobs to a specific queue, improving job routing control.

@talboren talboren merged commit 499abad into main Nov 20, 2024
13 checks passed
@talboren talboren deleted the 2557-bug-incidents-async-process-with-arq branch November 20, 2024 12:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working size:XS This PR changes 0-9 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[🐛 Bug]: Incidents async process with ARQ
2 participants